package me.zhengjie.cron;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.config.RegisterAddressConfig;
import me.zhengjie.domain.LayUpService;
import me.zhengjie.domain.PalletService;
import me.zhengjie.domain.ProStationService;
import me.zhengjie.dto.sqlServer.Pallet;
import me.zhengjie.modbusTCP.LayUpTCP;
import me.zhengjie.modbusTCP.NoThreeLayUpTcp;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class NoThreeLayUpBCron {

    private final LayUpService layUpService;
    private final PalletService palletService;
    private final NoThreeLayUpTcp noThreeLayUpTcp;
    private final ProStationService proStationService;


    @Scheduled(fixedDelay = 2000)
    public void startAsyncProcess(){
        // 传感器和启动按钮
        try {
            String stationCode = proStationService.findById(6).getStationCode();
            Integer startButtonValue = noThreeLayUpTcp.readHoldingRegisters(RegisterAddressConfig.noThreeLayUpBButton);
            Integer successBinding = noThreeLayUpTcp.readHoldingRegisters(RegisterAddressConfig.noThreeSuccessReadBindingPalletB);
            if (startButtonValue != null && startButtonValue == 1 && successBinding!=null && successBinding == 1){
                log.info("叠合结束，工作站编码:{}",stationCode);
                // 查找最新的载盘
                Pallet newPallet = palletService.findLastUpdatePalletByStationCode(stationCode);
                // 查找
                layUpService.finishLayUp(newPallet.getPalletCode());
                // 写入流向信息
                noThreeLayUpTcp.writeWithRetry(RegisterAddressConfig.noThreeLayUpBFlowTo, newPallet.getFlowTo(), 5);
            }
        } catch (Exception e) {
            log.error("叠合区定时器出错，错误原因：{}",e.toString());
        }
    }
}
